std::unordered_map::operator[]

From Cppreference

Jump to: navigation, search
T& operator[]( const Key& key );
(1) (since C++11)
T& operator[]( Key&& key );
(2) (since C++11)

Inserts a new element to the container using key as the key and default constructed mapped value and returns a reference to the newly constructed mapped value. If an element with key key already exists, no insertion is performed and a reference to its mapped value is returned.

1) Essentially performs (insert(std::make_pair(key, T())).first)->second.

2) Essentially performs (insert(std::make_pair(std::move(key), T())).first)->second.

Contents

[edit] Parameters

key - the key of the element to find

[edit] Return value

reference to the mapped value of the new element if no element with key key existed. Otherwise a reference to the mapped value of the existing element is returned.

[edit] Complexity

[edit] See also

access specified element with bounds checking
(public member function)

[edit] Example

#include <unordered_map>
 
int main()
{
    std::unordered_map<char, int> map;
 
    map['a'] = 1;  //map = (a, 1)
    map['b'] = 2;  //map = (a, 1), (b, 2)
    map['a'] = 42; //map = (a, 42), (b, 2)
}
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages